package com.example.musicplayer


import android.annotation.SuppressLint
import android.os.Bundle
import androidx.core.app.NotificationCompat
import androidx.appcompat.app.AppCompatActivity
import android.media.MediaPlayer
import android.provider.MediaStore
import android.view.View
import androidx.core.content.ContextCompat
import androidx.core.app.ActivityCompat
import android.util.Log
import android.content.pm.PackageManager
import android.Manifest
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Build
import android.os.IBinder
import android.widget.Button
import java.io.IOException
import android.widget.TextView
import kotlin.concurrent.thread
import android.widget.SeekBar
import kotlinx.coroutines.channels.Channel


class MainActivity : AppCompatActivity(), ServiceConnection {

    val TAG = "MainActivity"
    var binder: MusicService.MusicBinder? = null
    val Channel_ID="my channel"
    val Notification_ID=1

    @SuppressLint("MissingInflatedId")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)


        if (ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.READ_MEDIA_AUDIO
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            ActivityCompat.requestPermissions(
                this,
                arrayOf(Manifest.permission.READ_MEDIA_AUDIO),
                0
            )
        } else {
            startMusicService()
        }

        val seekBar = findViewById<SeekBar>(R.id.seekBar)
        seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                if (fromUser) {
                    binder?.currentPosition = progress
                }
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {}
            override fun onStopTrackingTouch(seekBar: SeekBar?) {}
        })
        if (ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.READ_MEDIA_AUDIO
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            ActivityCompat.requestPermissions(
                this,
                arrayOf(Manifest.permission.READ_MEDIA_AUDIO),
                0
            )
        } else {
            startMusicService()
            createNotificationChannel()  // 创建通知频道
        }


        val radio = findViewById<Button>(R.id.radio)
        radio.setOnClickListener {
            val notificationManager :NotificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            val builder: Notification.Builder
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                val notificationChannel = NotificationChannel(Channel_ID, "test", NotificationManager.IMPORTANCE_HIGH)
                notificationManager.createNotificationChannel(notificationChannel)
                builder = Notification.Builder(this, Channel_ID)
            } else {
                builder = Notification.Builder(this)
            }

            val intent = Intent(this,MainActivity::class.java)
            val pendingIntent = PendingIntent.getActivity(this, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)

            val notification:Notification=builder.setSmallIcon(R.drawable.ic_notification)
                   .setContentTitle("musicname")
                   .setContentText(binder!!.musicName)
                   .setPriority(Notification.PRIORITY_HIGH)
                   .setContentIntent(pendingIntent)
                   .build()// set content text
            notificationManager.notify(Notification_ID, notification)
        }
    }


    fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val notificationChannel = NotificationChannel(
                Channel_ID,
                "My Channel Name",
                NotificationManager.IMPORTANCE_DEFAULT
            ).apply {
                description = "Channel description"
            }
            val notificationManager = getSystemService(NotificationManager::class.java)
            notificationManager.createNotificationChannel(notificationChannel)
        }
    }
    fun startMusicService() {
        val intent = Intent(this,MusicService::class.java)
        intent.putExtra(MusicService.Commoned,1)
        startService(intent)
        bindService(intent,this, BIND_AUTO_CREATE)
    }
    fun onPlay(v: View) {
        val intent = Intent(this,MusicService::class.java)
        intent.putExtra(MusicService.Commoned,1)
        startService(intent)
    }

    fun onPause(v: View) {
        val intent = Intent(this,MusicService::class.java)
        intent.putExtra(MusicService.Commoned,2)
        startService(intent)
    }

    fun onNext(v: View) {
        val intent = Intent(this,MusicService::class.java)
        intent.putExtra(MusicService.Commoned,4)
        startService(intent)
    }

    fun onStop(v: View) {
        val intent = Intent(this,MusicService::class.java)
        intent.putExtra(MusicService.Commoned,3)
        startService(intent)
    }

    fun onPrevious(v: View) {
        val intent = Intent(this,MusicService::class.java)
        intent.putExtra(MusicService.Commoned,5)
        startService(intent)
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        startMusicService()
    }


    override fun onDestroy() {
        super.onDestroy()
//        stopService(Intent(this,MusicService::class.java))
        unbindService(this)

    }

    override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
        binder=service as MusicService.MusicBinder
        thread {
            while (binder!=null){
                Thread.sleep(1000)
                runOnUiThread {
                    val seekBar=findViewById<SeekBar>(R.id.seekBar)
                    seekBar.max=binder!!.duration
                    seekBar.progress=binder!!.currentPosition
                    val textView_mm=findViewById<TextView>(R.id.textView_mm)
                    textView_mm.text=binder!!.musicName
                    val textView_count=findViewById<TextView>(R.id.textView_count)
                    textView_count.text="${binder!!.currentIndex+1}/${binder?.size }"
                }
            }
        }
    }
    override fun onServiceDisconnected(name: ComponentName?) {
        binder=null
    }

}

